<style lang='sass'>
  @import './ecstyle.scss'
</style>
<template>
  <div class="" id="ec-edit" style="position: relative;top: -60px;z-index: 999;" v-loading="loading">
    <!-- 编辑区域头部操作按钮 -->
    <el-header class="ec-edit-header">
      <span>企业主页编辑</span>
      <el-button size="mini" icon="el-icon-back" @click="back">返回</el-button>
      <el-button size="mini" icon="el-icon-view" @click="previewEc">预览</el-button>
      <el-button size="mini" icon="el-icon-delete" @click="clearEc">清空</el-button>
      <el-button size="mini" icon="el-icon-tickets" @click="publishEc">发布</el-button>

      <label>模板</label>
      <div class="color-templ">
        <span v-for="(vlaue, index) in 4" :class="{'active': themeIndex === index}" class="" @click="selectTheme(index)" :key="index"></span>
      </div>
    </el-header>
    <el-main :class="classTheme" style="padding: 0px;">
      <!-- 企业banner，包含logo，企业名称，企业资质 -->
      <div class="banner-logo">
        <div class="ec-logo">
          <file-upload
            ref="upload"
            :is-display="true"
            list-type="picture-card"
            :limit="1"
            :maxSize="1"
            accept="image/*, .jpg, .png, .jpeg"
            v-model="ec.enterpriseLogo"
          >
            <span>LOGO</span>
          </file-upload>
        </div>
        <el-input
          disabled=""
          v-validate="'required|max:20'" name="企业名称"
          placeholder="企业名称(不多于20字)"
          v-model="ec.enterpriseName"
          clearable>
        </el-input>
        <el-select v-model="ec.enterpriseQualification" placeholder="企业资质" v-validate="'required'" name="企业资质">
          <el-option
            v-for="item in optionsGrade"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <!-- <el-input
          v-validate="'required'" name="企业资质"
          placeholder="企业资质，例如土地规划乙级资质证书（612017067）"
          v-model="ec.enterpriseQualification"
          clearable>
        </el-input> -->
      </div>
      <!-- 企业标签 -->
      <div class="ec-tags">
        <el-tag
          :key="tag.tagId"
          v-for="tag in dynamicTags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)">
          {{tag.tagName}}
        </el-tag>
        <el-autocomplete
          class="input-new-tag"
          v-if="inputVisible"
          ref="saveTagInput"
          popper-class="my-autocomplete"
          v-model="inputValue"
          placeholder="标签关键字"
          style="width: 150px;"
          :fetch-suggestions="querySearchAsync"
          @select="handleSelect"
          @keyup.enter.native="handleInputConfirm"
        >
        <template slot-scope="{ item }">
          <div class="name">{{ item.tagName }}</div>
        </template>
        </el-autocomplete>
        <!-- <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input> -->
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新标签</el-button>
      </div>
      <!-- 企业简介 -->
      <div class="ec-profile" :class="{'echome-validate-err': errors.has('企业简介')}">
        <h2>企业简介</h2>
        <el-input
          v-validate="'required|max:500'" name="企业简介"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8}"
          placeholder="请输入内容,不多于500字"
          v-model="ec.enterpriseSummary">
        </el-input>
      </div>

      <!-- 企业联系方式 -->
      <div class="ec-contact">
        <h2>联系我们</h2>
        <div class="">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="ec-contact-card" :class="{'border-red': errors.has('联系人姓名')}">
                <label>联系人</label>
                <el-input
                  v-validate="'required|max:10'" name="联系人姓名"
                  placeholder="不多于10个字"
                  v-model="ec.enterpriseContacts"
                  clearable>
                </el-input>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="ec-contact-card" :class="{'border-red': errors.has('联系方式')}">
                <label>联系方式</label>
                <el-input
                  v-validate="'required|fax'" name="联系方式"
                  placeholder="请输入联系方式"
                  v-model="ec.enterpriseContactsPhone"
                  clearable>
                </el-input>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="ec-contact-card" :class="{'border-red': errors.has('企业邮箱')}">
                <label>企业邮箱</label>
                <el-input
                  v-validate="'required|email'" name="企业邮箱"
                  placeholder="请输入企业邮箱"
                  v-model="ec.email"
                  clearable>
                </el-input>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="ec-contact-card" :class="{'border-red': errors.has('企业地址')}">
                <label>企业地址</label>
                <city-cascader
                  ref="city"
                  v-validate="'required|city'" name="企业地址"
                  v-model="ec.cityName"
                  :provinceCode.sync="ec.provinceCode"
                  :areaCode.sync="ec.areaCode"
                  :cityCode.sync="ec.cityCode"
                ></city-cascader>
                <el-input
                  v-validate="'required|max:40'" name="企业详细地址"
                  placeholder="详细地址(不多于40个字)"
                  v-model="ec.enterpriseAddress"
                  clearable>
                </el-input>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <product-display v-model="ec.mscsProductDisplayList" ref="productdisplay"></product-display>
      <ec-expert v-model="ec.mscsEnterpriseExpertList" ref="ecexpert"></ec-expert>
      <quality-case v-model="ec.mscsBusinessCasesList" ref="qualitycase"></quality-case>
      <solution v-model="ec.mscsSolutionProgramList" ref="solution"></solution>
      <ec-honor v-model="ec.mscsEnterpriseHonorList" ref="echonor"></ec-honor>
    </el-main>
    <!-- <viewer  :images="[ec.enterpriseLogo]"
         @inited="inited"
         class="viewer" ref="viewer" v-show="false">
     <template slot-scope="scope">
       <img v-for="(src, index) in scope.images" :src="src" :key="index">
     </template>
   </viewer> -->
    <back-top></back-top>
  </div>
</template>

<script>
import axios from 'axios'
import EcExpert from './blockcomponents/EcExpert'
import EcHonor from './blockcomponents/EcHonor'
import ProductDisplay from './blockcomponents/ProductDisplay'
import QualityCase from './blockcomponents/QualityCase'
import Solution from './blockcomponents/Solution'

let v = async function (self) {
  let result1 = await self.$refs.productdisplay.validate()
  if (result1) {
    for (let i = 0; i < self.ec.mscsProductDisplayList.length; i++) {
      if (self.ec.mscsProductDisplayList[i].image < 20) {
        self.$message({
          message: '请上传产品展示相应图片，或删除多余项',
          type: 'warning'
        })
        return false
      }
    }
  } else {
    self.$message({
      message: '产品展示填写不正确或不完整，如果暂时填写不完整，请删除该项',
      type: 'warning'
    })
    return false
  }

  let result2 = await self.$refs.ecexpert.validate()
  if (result2) {
    for (let i = 0; i < self.ec.mscsEnterpriseExpertList.length; i++) {
      if (self.ec.mscsEnterpriseExpertList[i].image < 20) {
        self.$message({
          message: '请上传企业专家相应图片，或删除多余项',
          type: 'warning'
        })
        return false
      }
    }
  } else {
    self.$message({
      message: '企业专家填写不正确或不完整，如过暂时填写不完整，请删除该项',
      type: 'warning'
    })
    return false
  }

  let result3 = await self.$refs.qualitycase.validate()
  if (!result3) {
    self.$message({
      message: '优质案例填写不正确或不完整，如过暂时填写不完整，请删除该项',
      type: 'warning'
    })
    return false
  }

  let result4 = await self.$refs.solution.validate()
  if (!result4) {
    self.$message({
      message: '解决方案填写不正确或不完整，如过暂时填写不完整，请删除该项',
      type: 'warning'
    })
    return false
  }

  let result5 = await self.$refs.echonor.validate()
  if (result5) {
    for (var i = 0; i < self.ec.mscsEnterpriseHonorList.length; i++) {
      if (self.ec.mscsEnterpriseHonorList[i].image < 20) {
        self.$message({
          message: '请上传企业荣誉相应图片，或删除多余项',
          type: 'warning'
        })
        return false
      }
    }
  } else {
    self.$message({
      message: '企业荣誉填写不正确或不完整，或删除多余项',
      type: 'warning'
    })
    return false
  }
  return true
}

let getData = async function (self) {

  // 获取主页内容
  let ec = await axios.post('/mscs/home/findEnterpriseContentById', self.$paramsConvert({userId: self.$store.state.user.user.user.userId}))
  // 获取下面五个小块内容
  let ecChild = await axios.post('/mscs/home/findEnterpriseOtherData', self.$paramsConvert({enterpriseId: ec.data.data.data.enterpriseId}))
  self.ec = Object.assign({}, ec.data.data.data)
  self.ec.mscsProductDisplayList = ecChild.data.data.eroductDisplay
  self.ec.mscsEnterpriseExpertList = ecChild.data.data.enterpriseExpert
  self.ec.mscsEnterpriseHonorList = ecChild.data.data.enterpriseHonor
  self.ec.mscsSolutionProgramList = ecChild.data.data.solutionProgram
  self.ec.mscsBusinessCasesList = ecChild.data.data.businessCases
  self.themeIndex = parseInt(self.ec.theme)
  self.dynamicTags = JSON.parse(ec.data.data.data.tags)
}

let saveData = async function (self) {
  let ecRes = await axios.post('/mscs/home/findEnterpriseContentById', self.$paramsConvert({userId: self.$store.state.user.user.user.userId}))
  if (ecRes.data.code === 1) {
    self.ec.status = ecRes.data.data.data.status
    if (self.ec.status === 'REVOKE') {
      self.$alert('企业主页已被管理员关闭，发布后无法在企业列表中显示，请联系管理员处理', '提示', {
        confirmButtonText: '确定'
      })
    }
  }
  if (!self.isUp) {
    self.$message({
      showClose: true,
      message: '请上传企业logo',
      type: 'error'
    })
    return
  }
  self.loading = true
  // self.ec.tags = JSON.stringify(this.dynamicTags)
  self.ec.tags = JSON.stringify(self.dynamicTags.map(item => {
    return { tagName: item.tagName, tagId: item.tagId }
  }))
  self.ec.theme = self.themeIndex
  // this.ec.status = 'RELEASE' // 状态
  self.ec.isComment  = 'YES' // 状态
  self.ec.userId = self.$store.state.user.user.user.userId
  let saveRes = await axios.post('/mscs/home/addEnterpriseHomepageData', self.ec)
  return saveRes
}

export default {
  title: '企业主页编辑',
  name: 'ec-edit',
  data() {
    return {
      loading: false,
      themeIndex: 0, // 主题下标
      restaurants: [],
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      ec: {
        cityName: '',
        provinceCode: '',
        areaCode: '',
        cityCode: '',
        enterpriseName: '',
        enterpriseQualification: '',
        enterpriseLogo: '',
        enterpriseSummary: '', // 企业简介
        enterpriseContacts: '', // 企业联系人
        enterpriseContactsPhone: '', // 联系方式
        email: '', //企业邮箱
        enterpriseAddress: '', // 企业地址
        mscsProductDisplayList: [], // 企业展示
        mscsEnterpriseExpertList: [], //企业专家
        mscsEnterpriseHonorList: [], // 企业荣誉
        mscsSolutionProgramList: [], // 解决方案
        mscsBusinessCasesList: [], // 行业案例
      },
      optionsGrade: [{
          value: 'N',
          label: '非资质单位'
        },{
          value: 'A',
          label: '甲级'
        },{
          value: 'B',
          label: '乙级'
        },{
          value: 'C',
          label: '丙级'
        },{
          value: 'D',
          label: '丁级'
        }
      ],
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.loading = true
      vm.ec.enterpriseName = vm.$route.query.enterpriseName
      getData(vm).then(() => {}).catch((err) => {}).finally(() => {
        vm.loading = false
      })

    })
  },
  methods: {
    selectTheme (index) {
      this.themeIndex = index
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 选择的标签
    handleSelect (tag) {
      let index = this.dynamicTags.findIndex(item => item.tagName === tag.tagName)
      if (index < 0) {
        this.dynamicTags.push(tag)
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    handleInputConfirm() {
      if (this.inputValue.length === 0) {
        this.inputVisible = false;
        this.inputValue = '';
        return
      }
      axios.post('/mscs/tag/addTag', this.$paramsConvert({
        tagTypeId: 'B50C5A3E7E6011E8AC3FFA7DEC4CE400',
        tagName: this.inputValue
      })).then(res => {
        if (res.data.code === 1) {
          this.dynamicTags.push({tagName: this.inputValue, tagId: res.data.data})
          this.inputVisible = false;
          this.inputValue = '';
        } else {
          this.$codeError(res)
        }
      }).catch(error => {
        this.$catchError(error)
      })
    },
    // 取消输入
    handleInputCannel () {
      this.inputVisible = false;
      this.inputValue = '';
    },
    // 顶部四个按钮
    // 保存
    saveEc () {
      this.$validator.validate().then(result => {
        if (result) {
          v(this).then(result2 => {
            if (result2) {
              this.ec.theme = this.themeIndex
              this.ec.status = 'NORELEASE' // 状态
              this.ec.isComment  = 'YES' // 状态
              this.ec.tags = JSON.stringify(this.dynamicTags)
              this.ec.userId = this.$store.state.user.user.user.userId
              axios.post('/mscs/home/addEnterpriseHomepageData', this.ec).then(res => {
                if (res.data.code === 1) {
                  this.ec.enterpriseId = res.data.data.enterpriseId
                  this.ec.ctime = res.data.data.ctime
                  this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                } else {
                  this.$codeError(res)
                }
              }).catch(error => {
                this.$catchError(error)
              })
            }
          })
        } else {
          this.$message({
            showClose: true,
            message: this.$connErmsg(this.$validator.errors.items),
            type: 'error'
          })
        }
      })
    },
    // 预览
    previewEc () {
      this.$validator.validate().then(result => {
        if (result) {
          v(this).then(result2 => {
            if (result2) {
              if (!this.isUp) {
                this.$message({
                  showClose: true,
                  message: '请上传企业logo',
                  type: 'error'
                })
                return
              }
              let obj = JSON.parse(JSON.stringify(this.ec))
              obj.type = 'preview'
              obj.tags = JSON.stringify(this.dynamicTags)
              obj.mscsProductDisplayList = JSON.stringify(obj.mscsProductDisplayList)
              obj.mscsEnterpriseExpertList = JSON.stringify(obj.mscsEnterpriseExpertList)
              obj.mscsEnterpriseHonorList = JSON.stringify(obj.mscsEnterpriseHonorList)
              obj.mscsSolutionProgramList = JSON.stringify(obj.mscsSolutionProgramList)
              obj.mscsBusinessCasesList = JSON.stringify(obj.mscsBusinessCasesList)
              obj.theme = this.themeIndex
              localStorage.eccontent = JSON.stringify(obj)
              this.$nextTick(() => {
                const {href} = this.$router.resolve({
                  name: 'ecpriview'
                })
                window.open(href, '_blank')
              })
              
            }
          })
        } else {
          this.$message({
            showClose: true,
            message: this.$connErmsg(this.$validator.errors.items),
            type: 'error'
          })
        }
      })
    },
    // 清空
    clearEc () {
      this.$confirm('确认清空内容?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.ec = {
            enterpriseName: '',
            enterpriseQualification: '',
            enterpriseLogo: '',
            enterpriseSummary: '', // 企业简介
            enterpriseContacts: '', // 企业联系人
            enterpriseContactsPhone: '', // 联系方式
            email: '', //企业邮箱
            enterpriseAddress: '', // 企业地址
            mscsProductDisplayList: [], // 企业展示
            mscsEnterpriseExpertList: [], //企业专家
            mscsEnterpriseHonorList: [], // 企业荣誉
            mscsSolutionProgramList: [], // 解决方案
            mscsBusinessCasesList: [], // 行业案例
          }
          this.dynamicTags = []
          this.$refs.city.clearAll()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消清空'
          });
        });


    },
    // 发布
    publishEc () {
      this.$validator.validate().then(result => {
        if (result) {
          v(this).then(result2 => {
            if (result2) {
              if (!this.isUp) {
                this.$message({
                  showClose: true,
                  message: '请上传企业logo',
                  type: 'error'
                })
                return
              }
              saveData(this).then(res => {
                if (res.data.code === 1) {
                  this.ec.enterpriseId = res.data.data.enterpriseId
                  this.ec.ctime = res.data.data.ctime
                  this.ec.status = res.data.data.status
                  this.$message({
                    message: '保存成功',
                    type: 'success'
                  })
                } else {
                  this.$codeError(res)
                }
              }).catch(error => {
                this.$catchError(error)
              }).finally(() => {
                this.loading = false
              })

            }
          })
        } else {
          this.$message({
            showClose: true,
            message: this.$connErmsg(this.$validator.errors.items),
            type: 'error'
          })
        }
      })
    },
    // 根据输入框的内容，异步查询
    querySearchAsync(queryString, cb) {
      axios.post('/mscs/tag/findTag', this.$paramsConvert({tagTypeId: 'B50C5A3E7E6011E8AC3FFA7DEC4CE400', search: queryString})).then(res => {
        if (res.data.code === 1) {
          cb(res.data.data)
        } else {
          cb([])
        }
      }).catch(error => {
        this.$catchError(error)
      })
    },
    // 清除状态过滤
    createStateFilter(queryString) {
      return (state) => {
        return (state.enterpriseName.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    // 返回
    back () {
      this.$router.go(-1)
    }
  },
  computed: {
    classTheme () {
      let index = parseInt(this.themeIndex)
      if (index === 0) {
        return 'light-green-ec'
      } else if (index === 1) {
        return 'blue-ec'
      } else if (index === 2) {
        return 'dark-green-ec'
      } else if (index === 3) {
        return 'default-ec'
      }
      return ''
    },
    // 一下三个都是企业logo相关
    // authorization () {
    //   return this.$store.state.user.token
    // },
    // fileList () {
    //   if (this.ec.enterpriseLogo && this.ec.enterpriseLogo.length > 20) {
    //     return [{name: 'gerentouxiang.png', url: this.ec.enterpriseLogo}]
    //   } else {
    //     return []
    //   }
    // },
    isUp () {
      return this.ec.enterpriseLogo && this.ec.enterpriseLogo.length > 20
    }
  },
  components: {
    'ec-expert': EcExpert,
    'ec-honor': EcHonor,
    'product-display': ProductDisplay,
    'quality-case': QualityCase,
    'solution': Solution
  }
}
</script>
